<template>
  <div class="app-container">
    <flex-container size="10px">
      <!-- <template #header>
        <div class="container-header">
          <span>地址名称:</span>
          <el-input
            v-model="filterData.name"
            placeholder="请填写需要搜索的地址名称"
            style="width: 220px;"
          >
            <template #prepend>
              <el-select
                v-model="select"
                placeholder="Select"
                style="width: 115px"
              >
                <el-option label="Restaurant" value="1" />
                <el-option label="Order No." value="2" />
                <el-option label="Tel" value="3" />
              </el-select>
            </template>
          </el-input>
          &#x3000;
          <el-button type="primary" @click="SearchEvent">搜索</el-button>
        </div>
      </template> -->
      <template #default>
        <div class="container-body">
          <flex-container size="10px">
            <!-- <template #header>
              <p>
                当前已选择地址名称:&nbsp;
                <span style="color: var(--color-primary);">
                  {{ fullAreas.length ? fullAreas.join(" / ") : "空" }}
                </span>
              </p>
            </template> -->
            <el-row :gutter="20" class="h-full">
              <el-col :span="6" class="h-full">
                <area-check
                  :areasList="provinceList"
                  @change="handlerChange"
                  @formChaneg="formChaneg"
                  :level="1"
                />
              </el-col>
              <el-col :span="6" class="h-full">
                <area-check
                  :areasList="cityList"
                  @change="handlerChange"
                  @formChaneg="formChaneg"
                  :level="2"
                  :pid="ids[1]"
                />
              </el-col>
              <el-col :span="6" class="h-full">
                <area-check
                  :areasList="areasList"
                  @change="handlerChange"
                  @formChaneg="formChaneg"
                  :level="3"
                  :pid="ids[2]"
              /></el-col>
              <el-col :span="6" class="h-full">
                <area-check
                  :areasList="streenList"
                  @change="handlerChange"
                  @formChaneg="formChaneg"
                  :level="4"
                  :pid="ids[3]"
              /></el-col>
            </el-row>
          </flex-container>
        </div>
      </template>
    </flex-container>
    <m-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="430px"
      append-to-body
    >
      <Form ref="formRef" @submit="handlerSubmit" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </m-dialog>
  </div>
</template>

<script>
import {
  GetAreaCitys,
  AddAreaCity,
  EditAreaCity,
  DelAreaCity
} from "@/api/system/addressbase";
import Space from "@/components/Space/index.vue";
import AreaCheck from "./components/areaCheck.vue";
import Form from "./components/form.vue";
export default {
  components: { Space, AreaCheck, Form },
  data() {
    return {
      filInput: "",
      tableData: [],
      filterData: {
        deep: 0,
        pid: 0
      },
      provinceList: [],
      cityList: [],
      areasList: [],
      streenList: [],
      ids: {},
      fullAreas: [],
      dialogVisible: false
    };
  },
  methods: {
    handlerSubmit(fd) {
      this.dialogVisible = false;
      const { name, extName } = fd;
      let submitData = {
        pid: 0,
        deep: 0,
        name,
        extName
      };
      if (fd.formType == "add") {
        // 新增
        if (fd.parent) {
          const { id, deep } = fd.parent;
          const childDeep = deep + 1;
          submitData.pid = id;
          submitData.deep = childDeep;
        }
        // console.log(submitData, "submitData");
        AddAreaCity(submitData).then(() => {
          this.$message.success("添加成功!");
          this.updataList(fd);
        });
      } else {
        // 编辑
        console.log(fd);
        const { pid, id, deep } = fd;
        submitData.pid = pid;
        submitData.id = id;
        submitData.deep = deep;
        EditAreaCity(submitData).then(() => {
          this.$message.success("修改成功!");
          this.updataList(fd);
        });
      }
    },
    /**刷新数据 */
    async updataList(fd) {
      fd = { ...fd, parent: this.ids[fd.deep] };
      console.log(fd, "fd");
      const arrKey = ["provinceList", "cityList", "areasList", "streenList"];
      let result;
      switch (fd.formType) {
        case "add":
          this.filterData = {
            deep: fd.deep,
            pid: fd.parent ? fd.parent.id : 0
          };
          result = await this.GetAreas();
          this[arrKey[fd.deep]] = result;
          break;
        case "edit":
          this.filterData = {
            deep: fd.deep,
            pid: fd.parent ? fd.parent.id : 0
          };
          result = await this.GetAreas();
          this[arrKey[fd.deep]] = result;
          break;
        default:
          break;
      }
    },
    /**时间戳和序列号 */
    generateUniqueId() {
      let sequence = 0; // 用于记录当前序列号
      const maxSequence = 999; // 最大序列号
      const timestamp = Math.floor(Date.now() / 1000) % 1000; // 获取当前时间戳（秒），并限制在 0-999
      sequence = (sequence + 1) % (maxSequence + 1); // 自增序列号，循环到 0
      const uniqueId = (timestamp * 1000 + sequence) % 2147483647; // 确保在 Int32 范围内
      return uniqueId;
    },
    submitForm() {
      this.$nextTick(() => {
        this.$refs["formRef"].submitForm();
      });
    },
    async GetAreas() {
      var result = await GetAreaCitys(this.filterData);
      return result.data;
    },

    checkChange(data) {
      this.fullAreas = [];
      Object.entries(data).forEach(([key, value]) => {
        this.fullAreas.push(value.name);
      });
    },

    /**
     * 地址库相关的增加 删除 编辑
     * @param fd
     */
    formChaneg(fd) {
      // console.log(fd, this.ids);
      if (["add", "edit"].includes(fd.formType)) {
        this.dialogVisible = true;
        if (fd.formType == "edit") {
          this.$nextTick(() => {
            this.$refs.formRef.ruleForm = {
              ...fd.isActive,
              formType: fd.formType
            };
            console.log(
              this.$refs.formRef.ruleForm,
              "this.$refs.formRef.ruleForm"
            );
          });
        } else {
          this.$nextTick(() => {
            this.$refs.formRef.ruleForm = {
              extName: "",
              deep: fd.type - 1,
              parent: this.ids[fd.type - 1],
              formType: fd.formType
            };
            console.log(
              this.$refs.formRef.ruleForm,
              "this.$refs.formRef.ruleForm"
            );
          });
        }
      } else {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            console.log(fd.isActive, "删除的数据项");
            DelAreaCity({ id: fd.isActive.id }).then(() => {
              const arrKey = [
                "provinceList",
                "cityList",
                "areasList",
                "streenList"
              ];
              this.filterData = {
                deep: fd.isActive.deep,
                pid: fd.isActive.pid
              };
              this.GetAreas().then(result => {
                this[arrKey[fd.isActive.deep]] = result;
              });

              this.$message({
                type: "success",
                message: "删除成功!"
              });
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    async handlerChange(data) {
      this.filterData.deep = data.type;
      this.filterData.pid = data.isActive.id;
      this.ids[data.type] = {
        ...data.isActive,
        id: data.isActive.id,
        name: data.isActive.extName
      };
      for (var i = data.type; i < 4; i++) {
        this.ids[i + 1] = undefined;
      }
      const result = await this.GetAreas();
      /**
       * data.type
       * 1-省发生变化
       * 2-市发生变化
       * 3-区发生变化
       * 4-街道发生变化
       */
      switch (data.type) {
        case 1:
          this.areasList = [];
          this.streenList = [];
          this.cityList = result;
          break;
        case 2:
          this.streenList = [];
          this.areasList = result;
          break;
        case 3:
          this.streenList = result;
          break;
        case 4:
          this.checkChange(this.ids);
          break;
      }
    }
  },

  async created() {
    this.provinceList = await this.GetAreas();
  }
};
</script>

<style lang="scss" scoped>
$baseFontSize: 16px;
$contenetPad: 10px 20px;

.app-container {
  font-size: $baseFontSize;
  padding: $contenetPad;
  height: 100%;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;

  .container-header {
    background-color: white;
    padding: 10px 15px;
  }

  .container-body {
    background-color: white;
    // margin-top: 10px;
    height: 100%;
    padding: 20px 15px;
    border-radius: 5px;
    box-sizing: border-box;

    // .el-row {
    //   margin: 10px 0;
    // }
  }

  .area-tab {
    padding: 0px 10px;
    font-size: 12px;
    border-radius: 3px;
    background-color: var(--color-primary);
    color: white;
    cursor: pointer;
    transition: background-color 0.3s linear;

    &:hover {
      background-color: var(--color-primary-3);
    }
  }
}
.el-table {
  margin-top: 10px;
  // height: 0;
  // flex: 1;
}
</style>
